package com.carlinfo.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.swing.plaf.synth.SynthScrollBarUI;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class IOUtil
{
	private Logger logger = LogManager.getLogger();
	public String readFile(File souFile)
	{
		
		try
		{
			InputStream in = new FileInputStream(souFile);
			String fileStr =this.readFile(in);
			return fileStr;
		} catch (FileNotFoundException e)
		{
			logger.error("读取文件失败了;文件的路径:{}",souFile.getAbsolutePath() , e);
		}
		return "";
	
	}
	public String readFile(InputStream in)
	{
		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;
		try
		{
			InputStreamReader isr = new InputStreamReader(in,"UTF-8");
			br = new BufferedReader(isr);
			String line ="";
			while((line = br.readLine())!=null)
			{
				sb.append(line+"\r\n");
			}
		} catch (UnsupportedEncodingException e)
		{
			logger.error("读取文件内容失败了;", e);
		} catch (IOException e)
		{
			logger.error("读取文件内容失败了;", e);
		}catch (Exception e)
		{
			logger.error("读取文件内容失败了;", e);
		}finally
		{
			try
			{
				if(br!=null)
				{
					br.close();
					br = null;
				}
			} catch (IOException e)
			{
				logger.error("关闭失败了;",e);
			}
		}
		return sb.toString();
	}
	public static void main(String[] args)
	{
		
		
		File file = new File("a.txt");
		System.out.println("====="+file.getAbsolutePath());
		/*Classs.forName()
		 * 三种方法获取Class:   ps: 老师忘了一种 只写了两种
		 * ~IOUtil.class  类名.class
		 * ~ioUtil.getClass()
		 *  */
		System.out.println("==IOUtil.class==="+IOUtil.class);
		Class cla = IOUtil.class;
		/* 参数就是classpath的路径  获取的是这个文件在硬盘上的的绝对路径 */
		System.out.println("==Resource==="+cla.getResource("/config.json"));
		/* 输入流*/
		InputStream in = cla.getResourceAsStream("/config.json");
		
		IOUtil ioUtil = new IOUtil();
		File souFile = new File("D:\\项目空间\\自己\\userscenter\\src_config\\config.json");
		String fileStr = ioUtil.readFile(souFile);
		System.out.println("==基于路径="+fileStr);
		
		/*从ClassPath中读取 
	 	 * classpath中的文件,/表示的是根路径;参照物是:classpath
	 	 * classpath:指是javac编译后class文件存放的路径;
	 	 * class存储于硬盘上的某个目录;
	 	 * class文件还存储于jar包
	 	  * 如果文件在jar包中;也可以读取到硬盘上的目录
	 	 * IOUtil.class.getClassLoader().getClass().的返回值也是Class
	 	 * */
		InputStream is = IOUtil.class.getClassLoader().getClass().getResourceAsStream("/config.json");
		fileStr = ioUtil.readFile(is);
		System.out.println("==classpath=="+fileStr);
	}
}
